import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'
Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      needLogin: false
    }
  },
  {
    path: '/cate',
    name: 'Cate',
    component: () => import('../views/Cate'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('../views/Cart'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/user',
    name: 'User',
    component: () => import('../views/User'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/detail/:id',
    name: 'detail',
    component: () => import('../views/Detail'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('../views/Order'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactadd',
    name: 'contactadd',
    component: () => import('../views/ContactAdd'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactedit/:id',
    name: 'contactedit',
    component: () => import('../views/ContactEdit'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactlist',
    name: 'contactlist',
    component: () => import('../views/ContactList'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('../views/Search'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/searchlist',
    name: 'searchlist',
    component: () => import('../views/SearchList'),
    meta: {
      needLogin: false
    }
  }
]
const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    const token = localStorage.getItem('auth_token')
    if (token) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  } else {
    next()
  }
})
export default router
